package struts.utility;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.plaf.synth.SynthScrollBarUI;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import sun.awt.SunHints.Value;

/**
 * 解析struts-config.xml配置内容，存储到XMLBean
 * @author Administrator
 *
 */
public class ParseXML {

	public ParseXML() {
	}
	
	//测试
	public static void main(String[] args){
		try {
			Map<String, XMLBean> map = parse("WebContent/WEB-INF/struts-config.xml");
			
			Set<String> keySet = map.keySet();
			for(Iterator<String> it = keySet.iterator(); it.hasNext();){
				String actionPath = it.next();
				System.out.println(actionPath);
				System.out.println(map.get(actionPath));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static  Map<String, XMLBean> parse(String xmlPath) throws Exception{
		Map<String, XMLBean> map = new HashMap<String, XMLBean>();
		
		SAXBuilder saxBuilder = new SAXBuilder();
		Document doc = saxBuilder.build(xmlPath);//"WebContent/WEB-INF/struts-config.xml"
		Element root = doc.getRootElement();
		
		Element actionMappings = root.getChild("action-mapping");
		List<Element> actionList = actionMappings.getChildren();
		for(Element action:actionList){
			XMLBean xmlBean = new XMLBean();
			String actionName = action.getAttributeValue("name");
			String actionType = action.getAttributeValue("type");
			String actionPath = action.getAttributeValue("path");
			System.out.println("  actionMappings: actionName="+actionName+"; actionType="+actionType+"; actionPath="+actionPath);
			
			List<Element> forwardList = action.getChildren();
			Map<String, String> actionForwardMap = new HashMap<String,String>();
			for(Element forward:forwardList){
				String forwardName = forward.getAttributeValue("name");
				String forwardValue = forward.getAttributeValue("value");
				actionForwardMap.put(forwardName, forwardValue);
				System.out.println("    actionForwardMap:forwardName=" + forwardName +" forwardValue="+ forwardValue);
			}
			
			String beanType="";
			Element formbeans = root.getChild("formbeans");
			List<Element> beanList = formbeans.getChildren();
			for(Element bean:beanList){
				if(actionName.equals(bean.getAttributeValue("name"))){
					beanType = bean.getAttributeValue("type");
					System.out.println("    formbeans:beanName=" + actionName +" beanType="+ beanType);
					break;
				}
			}
			
			xmlBean.setFormBeanName(actionName);
			xmlBean.setFormBeanType(beanType);
			xmlBean.setActionName(actionName);
			xmlBean.setActionType(actionType);
			xmlBean.setActionPath(actionPath);
			xmlBean.setActionForwardMap(actionForwardMap);
			
			map.put(actionPath, xmlBean);
		}
		return map;
	}
}
